const {
  MOCK_TOKEN,
  SERVER_HTTP,
  HEADER_KEY_PREFIX,
  NEED_SKIP_WEIXIN_AUTH,
} = require('../../config')
const axios = require('axios')
const qs = require('qs')

module.exports = {

  routes: (router) => {
    router.post('/dispatch', async (ctx, next) => {
      let {method, url, params} = ctx.request.body
      const isWeixinAuthUrl = /^\/weixin\/auth/.test(url)
      const authToken = NEED_SKIP_WEIXIN_AUTH ?
            MOCK_TOKEN : ctx.cookies.get('authToken')

      url = /^http/g.test(url) ? url : SERVER_HTTP + url
      const config = {
        method, url,
        headers: {},
        data: qs.stringify(params || {})
      }
      config.headers[HEADER_KEY_PREFIX + 'authToken'] = authToken || ''
      const resp = await axios(config)
      if (process.env.NODE_ENV === 'development') { // debug info
        console.log(url, '| method:', method, '| data:', params)
      }
      ctx.body = isWeixinAuthUrl ? resp.request.res.responseUrl : resp.data
    })

    router.get('/dispatch', async (ctx, next) => {
      let query = ctx.query
      let path = ''
      for (let key in ctx.query) {
        path += key === 'path' ? query.path : `&${key}=${query[key]}`
      }

      const url = /^http/g.test(path) ? path : SERVER_HTTP + path
      const config = { method: 'get', url, headers: {} }
      const authToken = NEED_SKIP_WEIXIN_AUTH ?
            MOCK_TOKEN : ctx.cookies.get('authToken')
      config.headers[HEADER_KEY_PREFIX + 'authToken'] = authToken || ''
      const resp = await axios(config)
      if (process.env.NODE_ENV === 'development') { // debug info
        console.log(url, '| method: GET | data:')
      }
      ctx.body = resp.data
    })

    router.post('/api/signin', async (ctx, next) => {
      let req = ctx.request.body
      if (req.username === 'demo' && req.password === 'demo') {
        ctx.session.authUser = { username: 'demo' }
        ctx.body = { username: 'demo' }
      } else {
        ctx.status = 401
        ctx.body = { success: false }
      }
    })

    router.post('/api/saveToken', async function (ctx, next) {
      ctx.body = { success: true }
    })

    router.post('/api/signout', async (ctx, next) => {
      delete ctx.session.authUser
      ctx.body = { success: true }
    })

    // Add POST - /api/lang
    router.post('/api/lang', (ctx, next) => {
      let { locale } = ctx.request.body
      ctx.session.locale = { locale }
      ctx.body = { success: true }
    })

    // Add POST - /api/visit
    router.post('/api/visit', (ctx, next) => {
      let url = SERVER_HTTP + '/visit/mark'
      axios.post(url, Object.assign({}, {
        ip: ctx.ip || ''
      }, ctx.request.body))
      ctx.body = { success: true }
    })

  }
}
